<?php
/**
 * 创建人 : Forpastime
 * 创建时间: 2023/3/21 16:06
 * 个人主页 : http://forpastime.com
 */

namespace App\Controller\Admin;


use App\Annotation\AdminNode;
use App\Model\Node;
use App\Utils\Result;
use App\Utils\RoutesToNodes;
use App\Middleware\Auth\AdminTokenMiddleware;
use App\Middleware\Auth\AdminPowerMiddleware;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;


/**
 * @AdminNode(name="功能节点管理",isMenu=1,sort=5,style="layui-icon-share")
 *
 * @Middlewares({
 *      @Middleware(AdminTokenMiddleware::class),
 *      @Middleware(AdminPowerMiddleware::class)
 * })
 * @AutoController(prefix="admin/node")
 */
class NodeController
{
    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject()
     * @var Node
     */
    protected $node;
    /**
     * @Inject()
     * @var Redis
     */
    protected $redis;

    /**
     * @AdminNode(name="节点列表",isMenu="1",sort="31")
     *
     * @return mixed
     */
    public function index()
    {

        if($this->request->isMethod('get')){
            $nodes = $this->node->getNodeList([['type','=',1]]);
            $nodes = for_get_tree(for_obj_to_array($nodes), true);
            return Result::success($nodes);
        }

    }

    /**
     *
     * 接口节点列表
     * @return mixed
     */
    public function apiPower()
    {

        if($this->request->isMethod('get')){
            $nodes = $this->node->getNodeList([['type','=',2]]);
            $nodes = for_get_tree(for_obj_to_array($nodes), true);
            return Result::success($nodes);
        }

    }

    /**
     * @AdminNode(name="添加节点",isMenu="0")
     *
     * @return mixed
     */
    public function nodeAdd()
    {
        $param = $this->request->all();
        unset($param['show_pid']);
        $res = $this->node->insertNode($param);
        if($res){
            return Result::success();
        }else{
            return Result::error('添加失败');
        }
    }

    /**
     * @AdminNode(name="编辑节点")
     *
     * @return mixed
     */
    public function nodeEdit()
    {
        $param = $this->request->all();;
        if(!isset($param['id']) || empty($param['id'])){
            return Result::error('参数异常');
        }
        $res= $this->node->editNode($param);
        if($res['code']){
            return Result::success();

        }else{
            return Result::error('修改失败');
        }
    }

    /**
     * @AdminNode(name="节点删除")
     * @Middleware(TokenMiddleware::class)
     * 删除节点
     * @return mixed
     */
    public function nodeDel()
    {
        $param = $this->request->all();;
        if(!isset($param['id']) || empty($param['id'])){
            return Result::error('参数异常');
        }
        $res= $this->node->delNode($param['id']);
        if($res['code']){
            return Result::success();

        }else{
            return Result::error('删除失败');
        }
    }

    /**
     * @AdminNode(name="节点更新",isMenu=0,sort=30)
     * 更新所有功能路由到本地文件
     * @return mixed
     */
    public function updateRouteCache()
    {
        $adminNodes = RoutesToNodes::start();
        $nodes = $this->node->getOriginalNodeList();

        //后台添加的不管
        $newNodes = [];
        if(empty($nodes)){

            //第一次同步
            foreach ($adminNodes['rootNodes'] as $k=> $v){
                //新节点处理数据
                if($v['action_name']!='#'){
                    continue;
                }
                //顶级节点
                $v['node_name'] = $v['name'];
                $v['parent_id'] = 0;
                $v['is_menu']= $v['isMenu']==null || $v['isMenu']==0 ? 0:1;
                $v['style']= $v['style']!=null ?$v['style'] : '';
                $v['sort']= $v['sort']!=null ?$v['sort']: 20;
                unset($v['name'],$v['isMenu']);
                $pid = $this->node->insertNode($v);
                $adminNodes['rootNodes'][$k]['id']= $pid;

            }
            foreach ($adminNodes['adminNodes'] as $index => $item) {
                $adminNodes['adminNodes'][$index]['parent_id'] = 0;
                $adminNodes['adminNodes'][$index]['node_name'] = $item['name'];
                $adminNodes['adminNodes'][$index]['is_menu'] = ($item['isMenu'] == null || $item['isMenu'] == 0) ? 0 : 1;
                $adminNodes['adminNodes'][$index]['style'] =  !empty($item['style']) ?? '';
                $adminNodes['adminNodes'][$index]['sort'] =  $item['sort']!=null ?$item['sort']: 20;
            }

            foreach ($adminNodes['rootNodes'] as $k=> $v) {
                foreach ($adminNodes['adminNodes'] as $index => $item) {
                    if ($item['control_name'] == $v['control_name']) {
                        //找到父节点
                        $adminNodes['adminNodes'][$index]['parent_id'] = $v['id'];
                    }
                }
            }
            foreach ($adminNodes['adminNodes'] as $index =>$item){
                unset($adminNodes['adminNodes'][$index]['name'],$adminNodes['adminNodes'][$index]['isMenu']);
            }

            $res = $this->node->insertMultiple($adminNodes['adminNodes']);
            if($res){
                return Result::success($adminNodes);
            }else{
                return Result::error('存储节点失败');
            }
        }else{
            $rootNodes = [];
            $newNodes[] = [];

            //去掉类节点已存在
            foreach ($adminNodes['rootNodes'] as $index=> $item){
                foreach ($nodes as $val){
                    if($item['control_name']==$val['control_name'] && ($item['action_name']==$val['action_name'] || ($item['action_name']=='index'&& $val['action_name']=='#'))){//已存在根节点为“#”，但是注解节点根节点是"index"
                        //筛选已存入节点的路由节点
                        unset($adminNodes['rootNodes'][$index]);
                        continue;
                    }
                }
            }
            //去掉方法节点已存在
            foreach ($nodes as $val){
                foreach ($adminNodes['adminNodes'] as $index=> $item){
                    if($item['control_name']==$val['control_name'] && $item['action_name']==$val['action_name']){
                        //筛选已存入节点的路由节点
                        unset($adminNodes['adminNodes'][$index]);
                        continue;
                    }else{
                        $adminNodes['adminNodes'][$index]['parent_id'] = 0;
                        $adminNodes['adminNodes'][$index]['node_name'] = $item['name'];
                        $adminNodes['adminNodes'][$index]['is_menu'] = ($item['isMenu']==null||$item['isMenu']==0) ? 0:1;
                        $adminNodes['adminNodes'][$index]['style'] = $item['style']!=null ?$item['style']: '';
                        $adminNodes['adminNodes'][$index]['sort'] = $item['sort']!=null ?$item['sort']: 20;
                    }
                }
            }
            //筛选数据表nodes里的根节点

            foreach ($nodes as $val){
                if($val['parent_id']==0){
                    $rootNodes[] = $val;
                }
            }



            if(!empty($adminNodes['rootNodes'])){

                foreach ( $adminNodes['rootNodes'] as $index=> $item){
                    //新顶级节点处理数据
                    $item['node_name'] = $item['name'];
                    $item['parent_id'] = 0;
                    $item['is_menu']= ($item['isMenu']==null||$item['isMenu']==0)?0:1;
                    $item['sort']= $item['sort']!=null ?$item['sort']: 20;
                    $item['style']= $item['style']!=null? $item['style']:'';

                    unset($item['name'],$item['isMenu'],$item['parent']);
                    $pid = $this->node->insertNode($item);
                    $adminNodes['rootNodes'][$index]['id'] = $pid;
                }

                $rootNodes = array_merge($rootNodes,$adminNodes['rootNodes']);
                //统一处理父节点id问题
                foreach ($rootNodes as $val){
                    foreach ($adminNodes['adminNodes'] as $index=> $item){
                        if($item['control_name']==$val['control_name'] && $val['parent_id']==0){//&& ($val['action_name']=='#'||$val['action_name']=='index')
                            $adminNodes['adminNodes'][$index]['parent_id'] = $val['id'];//isset($adminNodes['adminNodes'][$index]['parent']) && $adminNodes['adminNodes'][$index]['parent']>0?$adminNodes['adminNodes'][$index]['parent']:$val['id'];
                        }
                    }
                }

            }else{
                //没有类节点匹配有父节点的数据库节点
                foreach ($rootNodes as $val){
                    foreach ($adminNodes['adminNodes'] as $index=> $item){
                        if($item['control_name']==$val['control_name'] && $val['parent_id']==0){//&& ($val['action_name']=='#'||$val['action_name']=='index')
                            $adminNodes['adminNodes'][$index]['parent_id'] = $val['id'];//isset($adminNodes['adminNodes'][$index]['parent']) && $adminNodes['adminNodes'][$index]['parent']>0?$adminNodes['adminNodes'][$index]['parent']:$val['id'];
                        }
                    }
                }

            }

            foreach ($adminNodes['adminNodes'] as $index =>$item){
                unset($adminNodes['adminNodes'][$index]['name'],$adminNodes['adminNodes'][$index]['isMenu'],$adminNodes['adminNodes'][$index]['parent']);
            }

            $res = $this->node->insertMultiple($adminNodes['adminNodes']);
            if($res){
                return Result::success($adminNodes);
            }else{
                return Result::error('存储节点失败');
            }

        }
    }
}